<template>
    <div class="musics">
        <div class="add" style="display: flex;justify-content: flex-end;">
            <el-button type="primary" size="default" @click="add_music"
                style="font-size: 30px;margin-right: 2vw;margin-bottom: 1vw;font-weight: bold;">+</el-button>

        </div>
        <el-table :data="list" style="width: 100%">
            <el-table-column label="收藏时间" width="180">

                <template #default="scope">
                    <div style="display: flex; align-items: center">

                        {{ scope.row.publish_time }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="图片" width="180">
                <template #default="scope">
                    <el-avatar icon="el-icon-user-solid" size="large" shape="circle"
                        :src="base_url + scope.row.Music_img" fit="fill"></el-avatar>

                </template>
            </el-table-column>
            <el-table-column label="名字" width="180">
                <template #default="scope">
                    {{ scope.row.musicname }}
                </template>
            </el-table-column>

            <el-table-column label="风格" width="180">
                <template #default="scope">
                    <el-tag type="success">{{ scope.row.style.language }}</el-tag>
                    <el-tag type="success">{{ scope.row.style.genre }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
                        编辑
                    </el-button>
                    <el-popconfirm title="确认删除?" confirm-button-text="确认" cancel-button-text="取消"
                        @confirm="handleDelete(scope.$index, scope.row)">
                        <template #reference>
                            <el-button size="small" type="danger">
                                删除
                            </el-button>
                        </template>
                    </el-popconfirm>

                </template>
            </el-table-column>

        </el-table>

        <div class="page">
            <el-pagination layout="prev, pager, next" v-model:current-page="currentPage"
                @current-change="handleCurrentChange" :page-size="5" :total="count" background />
        </div>
        <el-dialog style="background-color: rgba(255,255 , 255, 0.8);" v-model="dialogVisible" title="添加音乐" width="500"
            draggable>
            <el-form ref="formRef" :model="forms" :rules="rules" label-width="auto" style="max-width: 600px">
                <el-form-item label="上传方式">
                    <el-radio-group v-model="forms.Music_type" @change="choice">
                        <el-radio border value="0">本地音乐</el-radio>
                        <el-radio border value="1">网络音乐</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="音乐名称" prop="musicname">
                    <el-input v-model="forms.musicname" />
                </el-form-item>
                <el-form-item label="歌手" prop="singer">
                    <el-input v-model="forms.singer" />
                </el-form-item>
                <el-form-item label="风格" prop="style">
                    <el-select v-model="forms.style.language" placeholder="选择" style="width: 100px">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                    <el-select v-model="forms.style.genre" placeholder="选择" style="width: 100px">
                        <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="图片" prop="Music_img">
                    <el-upload ref="uploadref" class="avatar-uploader" :on-success="handleAvatarSuccess_img"
                        :action="base_url + '/essay/upload'" :show-file-list="false">
                        <img style="height: 150px;width: 150px;" v-if="forms.Music_img"
                            :src="base_url + forms.Music_img" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="本地上传" v-if="upload_may === 0" prop="local_address">
                    <el-upload class="upload-demo" :action="base_url + '/music'" :limit="1"
                        :on-success="handleAvatarSuccess_music">
                        <el-button type="primary">点击上传</el-button>

                    </el-upload>
                </el-form-item>
                <el-form-item label="网络地址" v-else prop="network_address">
                    <el-input v-model="forms.network_address" placeholder="" size="normal" clearable></el-input>

                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="upload_music(formRef)">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>


    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue"
import { Plus } from '@element-plus/icons-vue'
import { type FormInstance } from 'element-plus'
import { type Music_doc } from "@/types/Music"
import MusicStore from "@/store/MusicStore"
import { format } from "@/utils/formatTime"
const isEdit = ref(false)
const currentPage = ref(1)
const base_url = import.meta.env.VITE_APP_URL
const store = MusicStore()
const formRef = ref<FormInstance>()
const uploadref = ref()
const list = ref([])
const count = ref(0)
const dialogVisible = ref(false)
const forms = reactive<Music_doc>({
    musicname: "",
    singer: "",
    Music_type: "0",
    Music_img: "",
    style: {
        language: '',
        genre: "",
    },
    local_address: "",
    network_address: "",
    publish_time: Date.now()
})
onMounted(async () => {

    await getData()
})
watch(dialogVisible, (e) => {

    if (!e) {
        isEdit.value = false
        Object.assign(forms, {
            musicname: "",
            singer: "",
            Music_type: "0",
            Music_img: "",
            style: {
                language: '',
                genre: "",
            },
            local_address: "",
            network_address: "",
            publish_time: Date.now()
        })
    }

})
const getData = async () => {
    const result = await store.Get_Music_list(currentPage.value * 5 - 5)
    result.data.forEach((item: any, index: any) => {
        result.data[index].publish_time = format.formatDate(item.publish_time)
    });
    list.value = result.data
    count.value = result.count
    console.log(list.value)
}
//翻页
const handleCurrentChange = async () => {
    const result = await store.Get_Music_list(currentPage.value * 5 - 5)
    result.data.forEach((item: any, index: any) => {
        result.data[index].publish_time = format.formatDate(item.publish_time)
    });
    list.value = result.data
    count.value = result.count

}
let upload_may = ref(0)
let isplay = ref(false)
//表单校验规则
const validateStyle = (rules: any, value: any, callback: any) => {
    if (value.language.trim() == "" || value.genre.trim() == "") {
        callback(new Error("请选择完整"))
    } else {

        callback()
    }
}
const validateAddress = (rules: any, value: any, callback: any) => {
    if (value.trim() == "") {
        callback(new Error("请上传"))
    } else {

        callback()
    }
}
const rules = reactive({
    musicname: [
        { required: true, message: '必填字段', trigger: 'blur' },
    ],
    singer: [
        { required: true, message: '必填歌手', trigger: 'blur' },
        { min: 1, message: '必填歌手', trigger: 'blur' },
    ],
    Music_img: [
        { required: true, message: '上传图片', trigger: 'blur' },
    ],
    style: [
        { type: "object", required: true, validator: validateStyle, trigger: 'change' },
    ],
    local_address: [
        { type: "string", required: true, validator: validateAddress, trigger: 'change' },
    ],
    network_address: [
        { type: "string", required: true, validator: validateAddress, trigger: 'change' },
    ]



})
//风格-start--
const options = [
    {
        value: '国语',
        label: '国语',
    },
    {
        value: '英语',
        label: '英语',
    },
    {
        value: '日系',
        label: '日系',
    },
    {
        value: '韩语',
        label: '韩语',
    },
    {
        value: '粤语',
        label: '粤语',
    },
    {
        value: '小语种',
        label: '小语种',
    },
    {
        value: '闽南语',
        label: '闽南语'
    },
    {
        value: '法语',
        label: '法语',
    },
    {
        value: '拉丁语',
        label: 'vue',
    },

]
const options2 = [
    {
        value: '流行',
        label: '流行',
    },
    {
        value: '轻音乐',
        label: '轻音乐',
    },
    {
        value: '摇滚',
        label: '摇滚',
    },
    {
        value: '民谣',
        label: '民谣',
    },
    {
        value: '嘻哈',
        label: '嘻哈',
    },
    {
        value: '电子',
        label: '电子',
    },
    {
        value: '古典',
        label: '古典'
    },
    {
        value: '爵士',
        label: '爵士',
    },
    {
        value: '中国传统',
        label: '中国传统',
    },
    {
        value: '世界音乐',
        label: '世界音乐',

    }
]
//风格-end--

const choice = (e: any) => {
    console.log(e)
    if (e == 0) {
        upload_may.value = 0
    } else {
        upload_may.value = 1
    }
}
const add_music = () => {
    isEdit.value = false
    dialogVisible.value = true
}

//编辑
const handleEdit = (index: any, row: any) => {
    console.log(index, row)
    Object.assign(forms, {
        _id: row._id,
        musicname: row.musicname,
        singer: row.singer,
        Music_type: row.Music_type,
        Music_img: row.Music_img,
        style: row.style,
        local_address: row.local_address,
        network_address: row.network_address,
    })
    isEdit.value = true
    dialogVisible.value = true

}
//删除
const handleDelete = async (index: any, row: any) => {
    await store.Delete_music(row._id)
    handleCurrentChange()
}
//上传音频-----------start-------
const handleAvatarSuccess_img = (e: any) => {
    forms.Music_img = e.data.url
}
const handleAvatarSuccess_music = (e: any) => {
    forms.local_address = e.data.url
}
//上传音频-----------end-------

const upload_music = (formEl: FormInstance | undefined) => {
    console.log(forms, 'sssss')
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            if (isEdit.value) {
                console.log("修改")
                await store.Put_music(forms)

                //获取列表
                handleCurrentChange()
            } else {
                console.log("添加")
                currentPage.value = 1
                await store.add_doc(forms)
                //获取列表
                handleCurrentChange()

            }
            Object.assign(forms, {
                musicname: "",
                singer: "",
                Music_type: "0",
                Music_img: "",
                style: {
                    language: '',
                    genre: "",
                },
                local_address: "",
                network_address: "",
                publish_time: Date.now()
            })
            uploadref.value.clearFiles()
            dialogVisible.value = false

        } else {
        }
    })
}

</script>

<style scoped lang="scss">
.musics {
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);

    }



    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
        background-color: white;
    }
}

.page {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-top: 2vw;

}
</style>